from django.shortcuts import render
from rest_framework.viewsets import ViewSet, GenericViewSet
from rest_framework.mixins import RetrieveModelMixin, UpdateModelMixin
from rest_framework.decorators import action
from rest_framework.exceptions import APIException
from .serializer import UserMulLoginSerializer, UserMobileLoginSerializer, UserRegisterSerializer, UserSerializer, \
    UserGenderSerializer, UserUpdateSerializer, UserSignatureSerializer, UserHeaderSerializer, UserPhoneViewSerializer, \
    UpdatePWDSerializer
from utils.response import APIResponse
from utils.view import CommonUpdateModelMixin
from libs.send_tx_sms import get_code, send_sms_by_phone
from django.core.cache import cache
from .models import UserInfo
import re


class UserLoginView(ViewSet):
    def get_serializer(self, data):
        if self.action == 'mul_login':
            return UserMulLoginSerializer(data=data)
        return UserMobileLoginSerializer(data=data)

    def common_login(self, request):
        ser = self.get_serializer(data=request.data)
        ser.is_valid(raise_exception=True)
        token = ser.context.get('token')
        username = ser.context.get('username')
        icon = ser.context.get('icon')
        pk = ser.context.get('pk')
        mobile = ser.context.get('mobile')
        return APIResponse(token=token, username=username, icon=icon, id=pk, mobile=mobile)

    @action(methods=['POST'], detail=False)  # 多方式登入
    def mul_login(self, request):
        return self.common_login(request)

    @action(methods=['POST'], detail=False)  # 短信登入
    def mobile_login(self, request):
        return self.common_login(request)

    @action(methods=['GET'], detail=False)  # 查询手机号
    def mobile(self, request):
        try:
            mobile = request.query_params.get('mobile')
            UserInfo.objects.get(mobile=mobile)
            return APIResponse(msg='手机号存在')
        except Exception as e:
            raise APIException('手机号不存在')

    @action(methods=['GET'], detail=False)  # 发送短信
    def send_sms(self, request):
        mobile = request.query_params.get('mobile')
        if re.match(r'^1[3-9][0-9]{9}$', mobile):
            code = get_code()
            print(code)
            cache.set('sms_code_%s' % mobile, code)
            res = send_sms_by_phone(mobile, code)
            if res:
                return APIResponse(msg='短信发送成功', sms_code=code)
            return APIResponse(msg='短信发送失败', code=101)
        return APIResponse(msg='手机号不合法', code=102)


class PhoneView(ViewSet):
    @action(methods=['POST'], detail=False)
    def is_sms(self, request):
        code = request.data.get('code')
        mobile = request.data.get('mobile')
        old_code = cache.get('sms_code_%s' % mobile)
        if (code == old_code or code == '8888'):
            return APIResponse()
        else:
            return APIResponse(code=101, msg='验证码错误')


class PasswordView(GenericViewSet, CommonUpdateModelMixin):
    queryset = UserInfo.objects.all()
    serializer_class = UpdatePWDSerializer

    def update(self, request, *args, **kwargs):
        super().update(request, *args, **kwargs)
        user_id = request.GET.get('user_id')
        user = UserInfo.objects.filter(id=user_id).first()
        old_password = request.data.get('old_password')
        new_password = request.data.get('new_password')

        if user.check_password(old_password):
            user.set_password(new_password)
            user.save()
            return APIResponse(msg='修改成功')
        else:
            raise APIException('旧密码错误')


class UserRegisterView(ViewSet):
    @action(methods=['POST'], detail=False)  # 注册
    def mul_register(self, request):
        ser = UserRegisterSerializer(data=request.data)
        ser.is_valid(raise_exception=True)
        ser.save()
        token = ser.context.pop('token')
        username = ser.context.get('username')
        icon = ser.context.get('icon')
        pk = ser.context.get('pk')
        mobile = ser.context.get('mobile')
        return APIResponse(msg='注册成功', token=token, username=username, icon=icon, id=pk, mobile=mobile)


class UserView(GenericViewSet, RetrieveModelMixin):
    queryset = UserInfo.objects.all()
    serializer_class = UserSerializer


class UserGenderView(GenericViewSet, UpdateModelMixin):
    queryset = UserInfo.objects.all()
    serializer_class = UserGenderSerializer


class UserUpdateView(GenericViewSet, UpdateModelMixin):
    queryset = UserInfo.objects.all()
    serializer_class = UserUpdateSerializer


class UserSignatureView(GenericViewSet, UpdateModelMixin):
    queryset = UserInfo.objects.all()
    serializer_class = UserSignatureSerializer


class UserHeaderView(GenericViewSet, UpdateModelMixin):
    queryset = UserInfo.objects.all()
    serializer_class = UserHeaderSerializer


class UserPhoneView(GenericViewSet, UpdateModelMixin):
    queryset = UserInfo.objects.all()
    serializer_class = UserPhoneViewSerializer
